package com.mianyang.zhangsan.auth.exception;

import com.mianyang.zhangsan.common.base.R;
import com.mianyang.zhangsan.common.util.JsonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证异常处理
 * @author jiangjr
 * @date 2022-10-23
 */
@Component
public class AuthenticationEntryPointHandle implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        R result = new R(HttpStatus.FORBIDDEN.value(), "未登录或登录超时，请重新登录.");
        response.getWriter().write(JsonUtils.toString(result));
    }
}
